import { defineStore } from 'pinia'
import { asyncRouters, baiscRouters } from '@/router/routes'

/**
 * 判断账号是否包含路由权限
 * @param {*} permissions
 * @param {*} route
 * @returns
 */
function hasPermission(permissions, route) {
  const routeRoles = route.meta?.permission ? route.meta.permission : []
  if (!permissions.length || !permissions.length) {
    return false
  }
  if (route.meta && route.meta.permission) {
    return permissions.some((item) => routeRoles.includes(item))
  }
}

/**
 * 过滤路由
 * @param {} routerMap
 * @param {*} permissions
 * @returns
 */
function filterAsyncRoutes(routerMap = [], permissions) {
  let authorizedRouterSchema = []
  routerMap.forEach((route) => {
    if (hasPermission(permissions, route)) {
      const authorizedRouter = {
        component: route.component,
        meta: route?.meta,
        name: route?.name,
        path: route?.path,
        redirect: route?.redirect,
        hidden: route?.hidden,
      }
      if (route.children && route.children.length) {
        const childrenRouter = filterAsyncRoutes(route.children, permissions)
        console.log('childrenRouter', childrenRouter)
        authorizedRouter['children'] = childrenRouter
      }
      authorizedRouterSchema.push(authorizedRouter)
    }
  })
  return authorizedRouterSchema
}

export const usePermissionStore = defineStore('permission', {
  state: () => {
    return {
      routes: [],
      authorizedRouterSchema: [],
    }
  },

  actions: {
    generateRoutes(role = []) {
      const accessRoutes = filterAsyncRoutes(asyncRouters, role)
      this.authorizedRouterSchema = accessRoutes
      this.routes = baiscRouters.concat(accessRoutes)
      console.log(accessRoutes)
      return accessRoutes
    },
  },
})
